package com.mulanweb.handler.wechat;

import com.mulanweb.api.module.model.Token;
import com.mulanweb.db.common.Constant;
import com.mulanweb.handler.PostHandler;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * Created by Administrator on 2016/8/30.
 */
public class JsApiTicketHandler {

    public synchronized static  String getJsApiTicket(){
        Token accessToken = Token.dao.findById(2) ;
        if(accessToken !=null ){
            System.out.println("-----ticket---:"+accessToken.getValue());
            return accessToken.getValue() ;
        }
        return null ;
    }

    public synchronized static String refreshJsApiTicket(){
        Map<String,String> para = PostHandler.post(Constant.WeChatFinalValue.getJsApiTicket());
        if(para.containsKey("errcode")  &&  !("0".equals(para.get("errcode")) )){
            System.out.println("错误消息："+para.get("errorCN"));
        }else {
            if(para.containsKey("ticket")){
                Token jsApiTicket = Token.dao.findById(2);
                if(jsApiTicket != null){
                    jsApiTicket.setValue(para.get("ticket"));
                    Calendar today = Calendar.getInstance();
                    Date createTime = jsApiTicket.getCreateTime();
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(createTime);
                    if((calendar.get(Calendar.YEAR)) == today.get(Calendar.YEAR)
                            && calendar.get(Calendar.MONTH) == today.get(Calendar.MONTH)
                            && calendar.get(Calendar.DATE) == today.get(Calendar.DATE)){
                        jsApiTicket.setTodayCount(jsApiTicket.getTodayCount()+1);
                    }else{
                        jsApiTicket.setTodayCount(1);
                    }
                    jsApiTicket.setCreateTime(new Date());
                    if (jsApiTicket.update()) {
                        System.out.println("-------------------jsApiTicket刷新成功");
                        return jsApiTicket.getValue() ;
                    }
                }else{
                    jsApiTicket = new Token();
                    jsApiTicket.setValue(para.get("ticket"));
                    jsApiTicket.setTodayCount(1);
                    jsApiTicket.setCreateTime(new Date());
                    if(jsApiTicket.save()){
                        System.out.println("-------------------jsApiTicket保存成功保存成功");
                        return jsApiTicket.getValue() ;
                    }
                }
            }
        }
        return null ;
    }
}
